package com.libb.audio_video_func_comp.jcvideo.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.libb.audio_video_func_comp.R;
import com.libb.audio_video_func_comp.jcvideo.JCMediaManager;
import com.libb.audio_video_func_comp.jcvideo.bean.AudioNotify;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by libinbin on 2017/10/23.
 */

public class AudioPlayerService extends Service {
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private static final int CODE_NOTIFICATION = 200; //构建PaddingIntent的请求码,可用于关闭通知
    private NotificationManager mNotificationManager; //通知管理器
    public AudioBroadcastReceiver receiver;
    public final static String ACTION_BUTTON = "com.notification.intent.action.ButtonClick";
    public final static String ACTION_CLOSE = "com.notification.close";
    public final static String BOFANG_STATEE = "com.bofang.state";
    private AudioNotify audioNotify;
    private RemoteViews remoteViews;
    private Notification notification;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        EventBus.getDefault().register(this);
        return new MsgBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        JCMediaManager.instance().audioPlayerService = null;
        mNotificationManager.cancelAll();
        if(receiver!=null){
            unregisterReceiver(receiver);
        }
        EventBus.getDefault().unregister(this);
        return super.onUnbind(intent);
    }

    public class MsgBinder extends Binder {
        /**
         * 获取当前Service的实例
         * @return
         */
        public AudioPlayerService getService(){
            return AudioPlayerService.this;
        }
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    /**
     * 粘性事件
     * @param audioNotify
     */
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onAudioNotifyEvent(AudioNotify audioNotify){
        this.audioNotify = audioNotify;
        setIconUrl(audioNotify.iconUrl);
        createCustomNotification();
    }

    public void setIconUrl(String urlStr) {
        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(String... params) {
                try {
                    URL url = new URL(params[0]);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(6000);//设置超时
                    conn.setDoInput(true);
                    conn.setUseCaches(false);//不缓存
                    conn.connect();
                    int code = conn.getResponseCode();
                    Bitmap bitmap = null;
                    if(code==200) {
                        InputStream is = conn.getInputStream();//获得图片的数据流
                        bitmap = BitmapFactory.decodeStream(is);
                    }
                    return bitmap;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                if (result != null) {
                    remoteViews.setImageViewBitmap(R.id.notify_icon,result);
                    mNotificationManager.notify(CODE_NOTIFICATION,notification);
                }
            }
        }.execute(urlStr);
    }

    private void createCustomNotification() {
        //注册广播
        receiver = new AudioBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_BUTTON);
        intentFilter.addAction(ACTION_CLOSE);
        intentFilter.addAction(BOFANG_STATEE);
        registerReceiver(receiver, intentFilter);
        Intent intent = new Intent(getApplicationContext(), audioNotify.intentClass);
        //如果第二次获取并且请求码相同,如果原来已解决创建了这个PendingIntent,则复用这个类,并更新intent
        int flag = PendingIntent.FLAG_UPDATE_CURRENT;
        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 3, intent, flag);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.load_icon)
                .setContentIntent(contentIntent)
                .setContent(getRemoteView()); //自定义通知栏view的api是在3.0之后生效

        notification = builder.build();
        //打开通知
        mNotificationManager.notify(CODE_NOTIFICATION, notification);
    }

    /**
     * 创建RemoteViews,3.0之后版本使用
     *
     * @return
     */
    public RemoteViews getRemoteView() {
        remoteViews = new RemoteViews(getPackageName(), R.layout.audio_notify);
        remoteViews.setTextViewText(R.id.notify_title, audioNotify.title);
        //设置点击的事件
        Intent buttonIntent = new Intent(ACTION_BUTTON);
        PendingIntent intent_paly = PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.notify_bofang, intent_paly);
        Intent closeIntent = new Intent(ACTION_CLOSE);
        PendingIntent pCloseIntent = PendingIntent.getBroadcast(this, 4, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.notity_close, pCloseIntent);
        return remoteViews;
    }

    public class AudioBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_BUTTON)) {
                try {
                    if(mediaPlayer.isPlaying()){
                        mediaPlayer.pause();
                        remoteViews.setImageViewResource(R.id.notify_bofang,R.mipmap.notify_bofang1);
                        //通知播放器改变播放的ui
                        sendBroadcast(new Intent("change.player.state").putExtra("isplay",false));
                    }else{
                        mediaPlayer.start();
                        remoteViews.setImageViewResource(R.id.notify_bofang,R.mipmap.notify_bofang2);
                        sendBroadcast(new Intent("change.player.state").putExtra("isplay",true));
                    }
                    mNotificationManager.notify(CODE_NOTIFICATION,notification);
                }catch (Exception e){

                }
            }
            if(action.equals(ACTION_CLOSE)){
                mNotificationManager.cancelAll();
            }
            if(action.equals(BOFANG_STATEE)){
                int playState = intent.getIntExtra("playState",-1);
                //暂停
                if(playState == 5){
                    remoteViews.setImageViewResource(R.id.notify_bofang,R.mipmap.notify_bofang1);
                }else{
                    remoteViews.setImageViewResource(R.id.notify_bofang,R.mipmap.notify_bofang2);
                }
                mNotificationManager.notify(CODE_NOTIFICATION,notification);
            }
        }
    }



}
